package com.demo.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*
    * 创建ShiroFilterFactoryBean
    * */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager getDefaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        /*
        * 设置安全管理器
        * */
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager);
        //添加Shiro内置过滤器
        /*
        * Shiro内置过滤器，可以实现权限相关的拦截器
        *   常用的过滤器：
        *       anon：无需认证可以访问
        *       authc：必须认证才可以访问
        *       user：如果使用rememberMe的功能可以直接访问
        *       pwems：该资源必须得到资源权限才看了一访问
        *       logout：退出登录
        * */
        Map<String , String> filterMap = new LinkedHashMap<String , String>();
        /*
        * key:是我们的url
        * value：是我们所对应的过滤器
        * */
        filterMap.put("/**" , "anon");
        //修改调整的登录页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        /* 设置安全管理器DI */
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /*
    * 创建DefaultWebSecurityManager
    * */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired LoginRealm getRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(getRealm);
        return securityManager;
    }

    /*
    * 创建realm
    * */
    @Bean
    public LoginRealm getRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm userRealm = new LoginRealm();
        /* 将家吗方式关联我们自定义的realm类 */
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return userRealm;
    }

    /* 设置密码加密 */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        /* 指定加密的方式 */
        matcher.setHashAlgorithmName("MD5");
        /* 指定加密的次数 */
        matcher.setHashIterations(3);
        /* 使用设置编码 */
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
}
